<?php

namespace app\essayhandle\controller;

use think\Config;
use think\Db;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

use AlibabaCloud\Airec;
use think\Exception;

class Addessay
{
    //mongo对象
    public $mongo_obj;

    public function __construct()
    {
        try {
            $this->mongo_obj = Db::connect("db_mongo");
        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }

    //批量上传文章到mongo
    public function addEssayMongo($title, $content, $navigation_name, $tags_airec, $tag_arr)
    {
        try {

            //链接mongo文章集合item
            $mongo_obj = $this->mongo_obj->name("item");

            //添加到mongo的数据
            $add_mongo_data = [];

            $add_mongo_data['title'] = $title;
            $add_mongo_data['content'] = $content;

            //文章大图
            $add_mongo_data['type'] = 1;

            $add_mongo_data['author_id'] = '57fc95397f0827007dc5856f9c43e5f6';

            $add_mongo_data['img_url'] = [];

            $add_mongo_data['video_url'] = '';

            $add_mongo_data['share_numbers'] = 0;

            $add_mongo_data['remark_numbers'] = 0;

            $add_mongo_data['favour_numbers'] = 0;

            $add_mongo_data['read_numbers'] = 0;

            $add_mongo_data['pub_time'] = time();

            $add_mongo_data['vote'] = [];

            $add_mongo_data['airec_type'] = 0;

            $add_mongo_data['is_read'] = 0;

            $add_mongo_data['item_type'] = 'article';

            $scene_id = Db::connect('db_mongo')
                ->name('item_navigation')
                ->where(['navigation_name' => $navigation_name])
                ->field('scene_id')
                ->find();

            //场景id
            $add_mongo_data['scene_id'] = $scene_id['scene_id'];

            //$add_mongo_data['duration'] = 35;

            //内容最后修改的时间
            $add_mongo_data['last_modify_tim'] = $add_mongo_data['pub_time'];

            //权重，提高推荐率
            $add_mongo_data['weight'] = 1;


            $add_mongo_data['tags_airec'] = $tags_airec;

            //标签(本地用)
            $add_mongo_data['tag_arr'] = $tag_arr;

            $add_mongo_data['channel'] = $navigation_name;

            $add_mongo_data['click_cnt'] = 0;

            $add_mongo_data['like_cnt'] = 0;

            $add_mongo_data['unlike_cnt'] = 0;

            $add_mongo_data['comment_cnt'] = 0;

            $add_mongo_data['share_cnt'] = 0;

            $add_mongo_data['skip_type'] = 3;

            $add_mongo_data['classify_type'] = 1;

            $add_mongo_data['classify_name'] = $navigation_name;

            $add_mongo_data['classify_scene_id'] = $scene_id['scene_id'];

            $add_mongo_data['now_url'] = 'http://www.baidu.com';

            $add_mongo_data['item_count'] = getMid('item');

            $result = $this->mongo_obj->name('item')->insertGetId($add_mongo_data);

            return $result;

//            if ($result) {
//                //返回给前端的数据
//                $successBack = [];
//                $successBack['msg'] = '添加新闻成功';
//                $successBack['info'] = $result;
//                successBack($successBack);
//            } else {
//                throw new Exception('添加新闻失败', 1);
//            }

        } catch (\Exception $exception) {
            errorBack($exception);
        }
    }


    //批量上传文章到阿里云智能推荐
    public function updateItemAirec()
    {

        try {
            //链接mongo文章集合item
            $mongo_obj = $this->mongo_obj->name("item");

            //获取上传的数据(未读，未上传)
            $result = $mongo_obj->where(['airec_type' => 0, 'is_read' => 0])->select();

            //读取到的id的集合,没有则为空数组
            $id = [];
            if (!$result) {
                throw new Exception('没有需要更新的数据');
            }

            //将数据更新为已读

            //批量更新读取到的数据为已读
            foreach ($result as $key => $value) {
                $id[] = $value['id'];
            }
            //批量更新读取到的数据为已读
            $updateMongo = $mongo_obj->where('id', 'in', $id)->update(['is_read' => 1]);

            if (!$updateMongo) {
                throw new Exception('上传阿里云智能推荐失败');
            }


            //拼出需要上传的文档
            $content = [];

            //遍历结果，拼凑除上传到阿里云的文档
            foreach ($result as $value) {
                $add = [];
                $add['cmd'] = 'add';
                $add['fields'] = [];
                $add['fields']['item_id'] = $value['id'];
                $add['fields']['item_type'] = $value['item_type'];
                $add['fields']['status'] = '1';
                $add['fields']['scene_id'] = $value['scene_id'];
                $add['fields']['pub_time'] = $value['pub_time'];
                $add['fields']['title'] = $value['title'];
                $add['fields']['weight'] = $value['weight'];
                $add['fields']['tags'] = $value['tags_airec'];
                $add['fields']['author'] = $value['author_id'];
                $add['fields']['content'] = $value['content'];
                $add['fields']['channel'] = $value['channel'];
                $add['fields']['click_cnt'] = 0;
                $add['fields']['like_cnt'] = 0;
                $add['fields']['unlike_cnt'] = 0;
                $add['fields']['comment_cnt'] = 0;
                $add['fields']['share_cnt'] = 0;

                if (isset($value['duration'])) {
                    $add['fields']['duration'] = $value['duration'];
                }

                $content[] = $add;
            }

            $airceResult = $this->uploadingAirec($content, 'item');

            if ($airceResult) {

                //批量更新读取到的数据为上传阿里云成功
                $updateMongo = $mongo_obj->where('id', 'in', $id)->update(['airec_type' => 1]);

                //返回给前端的数据
                $successBack = [];
                $successBack['msg'] = '上传阿里云智能推荐成功';
                successBack($successBack);
            } else {
                throw new Exception('上传阿里云智能推荐失败');
            }

        } catch (\Exception $exception) {
            //批量更新读取到的数据为上传阿里云成功
            errorBack($exception);
        } catch (ClientException $exception) {
            errorBack($exception);
        } catch (ServerException $exception) {
            errorBack($exception);
        }
    }

    //使用接口上传,更新,删除文档到智能推荐实例,$content是需要上传的文档,$collection_name需要上传的集合名
    public function uploadingAirec($content, $collection_name)
    {
        AlibabaCloud::accessKeyClient(Config::get('accessKeyId'), Config::get('accessKeySecret'))->asDefaultClient();
        $result = AlibabaCloud::roa()
            ->regionId('cn-beijing') // 指定请求的区域，不指定则使用客户端区域、默认区域
            ->product('Airec') // 指定产品
            ->version('2018-10-12') // 指定产品版本
            ->action('PushDocument') // 指定产品接口
            ->serviceCode('airec')
            ->endpointType('openAPI')
            ->method('POST') // 指定请求方式
            ->host('airec.cn-beijing.aliyuncs.com') // 指定域名则不会寻址，如认证方式为 Bearer Token 的服务则需要指定
            ->pathPattern('/openapi/instances/[InstanceId]/tables/[TableName]/actions/bulk') // 指定ROA风格路径规则
            ->withInstanceId(Config::get('InstanceId')) // 为路径中参数赋值，方法名：with + 参数
            ->withTableName($collection_name)
            ->body(json_encode($content))
            ->request();

        if ($result['Result'] == 1) {
            return true;
        } else {
            return false;
        }
    }

    //获取推荐的结果
    public function getAirecResult($query)
    {

        AlibabaCloud::accessKeyClient(Config::get('accessKeyId'), Config::get('accessKeySecret'))->asDefaultClient();

        $result = AlibabaCloud::roa()
            ->regionId('cn-beijing') // 指定请求的区域，不指定则使用客户端区域、默认区域
            ->product('Airec') // 指定产品
            ->version('2018-10-12') // 指定产品版本
            ->action('Recommend') // 指定产品接口
            ->serviceCode('airec')
            ->endpointType('openAPI')
            ->method('GET') // 指定请求方式
            ->options([
                'query' => $query,
            ])
            ->host('airec.cn-beijing.aliyuncs.com') // 指定域名则不会寻址，如认证方式为 Bearer Token 的服务则需要指定
            ->pathPattern('/openapi/instances/[InstanceId]/actions/recommend') // 指定ROA风格路径规则
            ->withInstanceId(Config::get('InstanceId')) // 为路径中参数赋值，方法名：with + 参数
            ->request();


        $result = $result->toArray();

        $item_id = [];
        //如果没有获取到数据，则返回空数组
        if ($result) {
            $result = $result['Result'];
            foreach ($result as $value) {
                $item_id[] = $value['ItemId'];
            }
        }

        return $item_id;
    }
}